package portal;

import java.io.IOException;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import java.util.Map;

import java.util.TimeZone;

import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;

import javax.faces.application.Application;
import javax.faces.context.FacesContext;

import oracle.stellent.ridc.IdcClient;
import oracle.stellent.ridc.IdcClientException;
import oracle.stellent.ridc.IdcContext;
import oracle.stellent.ridc.model.DataBinder;
import oracle.stellent.ridc.model.DataObject;
import oracle.stellent.ridc.model.DataResultSet;
import oracle.stellent.ridc.model.impl.DataResultSetRow;
import oracle.stellent.ridc.protocol.ServiceResponse;

import oracle.webcenter.content.integration.el.support.ValueWrapperImpl;

import org.apache.myfaces.trinidad.context.RequestContext;

import portal.bean.LocaleBean;

public class UtilsContent {
    public static TimeZone timezone = TimeZone.getTimeZone("GMT+7");
    public UtilsContent() {
        super();
    }
   
    public static void main(String[] agr) {
       
        getAttachfilesInfo("525", "APPSSCGOVVN162000217", Global.getIdcClient(), Global.getUserContext());
       
    }
    /**
     * @creator
     * @comment doc du lieu cua 1 bang trong csdl UCM
     * @param viewName ten view trong UCM
     * @param tableName ten bang du lieu trong UCM
     * @param client
     * @param userContext
     * @return
     */
    public static DataResultSet getViewInfor(String viewName, String tableName,
                                       IdcClient client,
                                       IdcContext userContext) {
        DataResultSet obj = null;
        try {
            DataBinder dataBinder = client.createBinder();
            dataBinder.putLocal("IdcService", "GET_SCHEMA_VIEW_VALUES");
            dataBinder.putLocal("schViewName", viewName.toUpperCase());
            ServiceResponse ridc_response;
            ridc_response = client.sendRequest(userContext, dataBinder);
            DataBinder binder = ridc_response.getResponseAsBinder();
            obj = binder.getResultSet(tableName.toUpperCase());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return obj;
    }
    /**
     * @creator
     * @comment
     */
    public static List<DataObject> getdsNgonngu() {
        List<DataObject> lstNgonngu =null;
        try {
            DataResultSet rs =
                getViewInfor("NGONNGU_VIEW", "NGONNGU", Global.getIdcClient(),
                             Global.getUserContext());
            lstNgonngu = rs.getRows();
        } catch (Exception e) {
            // TODO: Add catch code
            e.printStackTrace();
        }
        return lstNgonngu;
    }

    /**
     * @creator
     * @comment
     */
    public static List<DataObject> getdslinhvuc() {
        List<DataObject> lstLinhvuc =null;      
        try {
            DataResultSet rs =
                getViewInfor("VBCK_LINHVUC_VIEW", "VBCK_LINHVUC",
                             Global.getIdcClient(), Global.getUserContext());
            lstLinhvuc = rs.getRows();
        } catch (Exception e) {
            // TODO: Add catch code
            e.printStackTrace();
        }
        return lstLinhvuc;
    }

    /**
     * @creator
     * @comment
     */
    public static List<DataObject> getdsloaibanban() {
        List<DataObject> lstLoaivanban =null;
        try {
            DataResultSet rs =
                getViewInfor("VBCK_LOAI_VIEW", "VBCK_LOAI", Global.getIdcClient(),
                             Global.getUserContext());
            lstLoaivanban = rs.getRows();
        } catch (Exception e) {
            // TODO: Add catch code
            e.printStackTrace();
        }
        return lstLoaivanban;
    }

    /**
     * @creator
     * @comment
     */
    public static List<DataObject> getdscoquanbanhanh() {
        List<DataObject> lstCoquanbanhanh = null;
        try {            
            DataResultSet rs =
                getViewInfor("VBCK_CQBH_VIEW", "VBCK_CQBH", Global.getIdcClient(),
                             Global.getUserContext());
            lstCoquanbanhanh = rs.getRows();
        } catch (Exception e) {
            // TODO: Add catch code
            e.printStackTrace();
        }
        return lstCoquanbanhanh;
    }

    /**
     * @creator TuyenNT
     * @comment Thu tuc lay danh sach Chuyen muc tin tuc trong CMS
     * @return
     */
    public static List<DataObject> getdschuyenmuctin() {
        List<DataObject> lstchuyenmuc =null;
        try {
            DataResultSet rs =
                getViewInfor("CHUYENMUCTIN_VIEW", "CHUYENMUCTIN",
                             Global.getIdcClient(), Global.getUserContext());
            lstchuyenmuc = rs.getRows();
        } catch (Exception e) {
            // TODO: Add catch code
            e.printStackTrace();
        }
        return lstchuyenmuc;
    }
    /**
     * @conmment lay noi dung tu primary file cua tin tuc
     * @param dDocName
     * @return
     * @throws IdcClientException
     * @throws IOException
     */
    public static String getDocContent(String dID,String dDocName) throws IdcClientException,
                                                         IOException {
        String content = null;       
        IdcContext userContext = new IdcContext(Global.username);        
        DataResultSet drs =  UtilsContent.getDocInfo(dID, dDocName, Global.getIdcClient(), userContext);        
        if(drs!=null) {
            DataObject obj = drs.getRows().get(0);
            String primaryFileFormat = obj.get("dFormat");
            if(primaryFileFormat.equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document") || primaryFileFormat.equals("application/msword")) {
                DataBinder dataBinder = Global.getIdcClient().createBinder();

                dataBinder.putLocal("IdcService", "GET_DYNAMIC_CONVERSION");
                dataBinder.putLocal("IsJava", "0");

                dataBinder.putLocal("dDocName", dDocName);
                dataBinder.putLocal("RevisionSelectionMethod", "LatestReleased");

                ServiceResponse ridc_response;
                ridc_response =
                        Global.getIdcClient().sendRequest(userContext, dataBinder);
                content = ridc_response.getResponseAsString();
                //them webroot vao duong link anh co trong noi dung
                if (content.contains("/cs/groups/"))
                    content =
                            content.replaceAll("/cs/groups/", Global.getWebroot() + "/cs/groups/");               
            }
        }

        return content;
    }
    /**
     * @creator
     * @comment Thu tuc tim kiem noi dung trong UCM
     * @param queryString
     * @param sortField
     * @param numberofResult 0: is not set
     * @param startRow 0: is not set
     * @param endRow 0: is not set
     * @param sortOrder ASC, DESC
     * @param client
     * @param userContext
     * @return
     */
    public static DataResultSet SearchUCMContent(String queryString,
                                           String sortField,
                                           int numberofResult, int startRow,
                                           int endRow, String sortOrder,
                                           IdcClient client,
                                           IdcContext userContext) {

        DataResultSet obj = null;
        try {
            DataBinder dataBinder = client.createBinder();
            dataBinder.putLocal("IdcService", "GET_SEARCH_RESULTS");
            dataBinder.putLocal("QueryText", queryString);
            dataBinder.putLocal("SortField", sortField);
            if (numberofResult > 0)
                dataBinder.putLocal("ResultCount",
                                    String.valueOf(numberofResult));
            if (startRow > 0)
                dataBinder.putLocal("StartRow", String.valueOf(startRow));
            if (endRow > 0)
                dataBinder.putLocal("EndRow", String.valueOf(endRow));
            if (sortOrder != null && sortOrder.length() > 0)
                dataBinder.putLocal("SortOrder", sortOrder);
            ServiceResponse ridc_response;
            ridc_response = client.sendRequest(userContext, dataBinder);
            DataBinder binder = ridc_response.getResponseAsBinder();
            obj = binder.getResultSet("SearchResults");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return obj;
    }

    /**
     * @creator
     * @comment
     * @param dID
     * @param dDocName
     * @param client
     * @param userContext
     * @return
     */
    private static DataBinder docInfoService(String dID,String dDocName, IdcClient client,
                                           IdcContext userContext) {
        
        DataBinder obj = null;
        try {            
            DataBinder dataBinder = client.createBinder();
            dataBinder.putLocal("IdcService", "DOC_INFO");
            dataBinder.putLocal("dID", dID);
            if(!dDocName.isEmpty())
            dataBinder.putLocal("dDocName", dDocName);
          
            ServiceResponse ridc_response;
            ridc_response = client.sendRequest(userContext, dataBinder);
            obj = ridc_response.getResponseAsBinder();         
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return obj;
    }

    /**
     * @creator
     * @comment
     * @param dID
     * @param dDocName
     * @param client
     * @param userContext
     * @return
     */
    public static DataResultSet getAttachfilesInfo(String dID,String dDocName, IdcClient client,
                                           IdcContext userContext) {
        DataResultSet obj =null;
        DataBinder binder = docInfoService(dID,dDocName,client,userContext);
        if(binder!=null)
            obj = binder.getResultSet("manifest");        
        return obj;
    }

   
    /**
     * @creator
     * @comment
     * @param dID
     * @param dDocName
     * @param client
     * @param userContext
     * @return
     */
    public static  DataResultSet getDocInfo(String dID,String dDocName, IdcClient client,
                                           IdcContext userContext) {
        DataResultSet obj =null;
        DataBinder binder = docInfoService(dID,dDocName,client,userContext);
        if(binder!=null)
            obj = binder.getResultSet("DOC_INFO");        
        return obj;
        
    }

    /**
     * @creator
     * @comment
     * @param key
     * @param value
     */
    public static void setPageFlowScope(String key, Object value) {
        Map pageFlowScope =
            RequestContext.getCurrentInstance().getPageFlowScope();
        Object myObject = pageFlowScope.put(key, value);
    }

    /**
     * @creator
     * @comment
     * @param key
     * @return
     */
    public static Object getPageFlowScope(String key) {
        Map pageFlowScope =
            RequestContext.getCurrentInstance().getPageFlowScope();
        Object myObject = pageFlowScope.get(key);
        return myObject;
    }

    /**
     * @creator
     * @comment
     * @param dID
     * @param dDocName
     * @return
     */
    public static List<DataObject> listAttachfile(String dID, String dDocName) {
        List<DataObject> lstAttachFile = new ArrayList<DataObject>();
        DataResultSet drs =
            UtilsContent.getAttachfilesInfo(dID, dDocName, Global.getIdcClient(),
                                            Global.getUserContext());
        if(drs!=null)
            lstAttachFile= drs.getRows();
       return lstAttachFile;
    }

    /**
     * @creator
     * @comment
     * @param strDate
     * @return
     */
    public static Date convertDate(String strDate) {
        Date d =null;
        try {
            String day = strDate;
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS", LocaleBean.getCurrentInstance().getUserLocale());
            d = format.parse(day);
            format = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS", LocaleBean.getCurrentInstance().getUserLocale());
            day = format.format(d);
            d = format.parse(day);
            Calendar cal = Calendar.getInstance();
            cal.setTimeZone(timezone);
            cal.setTime(d);
            cal.add(cal.HOUR, 7);
            d = cal.getTime();
        } catch (ParseException pex) {
            // TODO: Add catch code
            pex.printStackTrace();
        } catch (Exception e) {
            // TODO: Add catch code
            e.printStackTrace();
        }
        return d;
    }

    /**
     * @creator
     * @comment
     * @param expression
     * @return
     */
    public static Object getValueExpression(String expression) {
        try {
            FacesContext fc = FacesContext.getCurrentInstance();
            Application app = fc.getApplication();
            ExpressionFactory elFactory = app.getExpressionFactory();
            ELContext elContext = fc.getELContext();
            ValueExpression valueExp;
            valueExp = elFactory.createValueExpression(elContext, expression, Object.class);
            Object result = valueExp.getValue(elContext);
            if (result instanceof ValueWrapperImpl) {
                ValueWrapperImpl value = (ValueWrapperImpl)valueExp.getValue(elContext);
                result = value.getValue();
            }
            return result;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
    /**
     * @creator
     * @comment
     * @param strdDocName
     * @param fielGetValue
     * @return
     */
    public static String contentMetaDataInfo(String strdDocName, String fielGetValue) {
        String imgDid = "";
        try {

            IdcContext userContext = new IdcContext(Global.username);

            // Create a new binder
            DataBinder dataBinder = Global.getIdcClient().createBinder();

            // Retrieve the file
            dataBinder.putLocal("IdcService", "DOC_INFO_LATESTRELEASE");
            dataBinder.putLocal("dDocName", strdDocName);
            dataBinder.putLocal("RevisionSelectionMethod", "LatestReleased");
            ServiceResponse ridc_response;
            ridc_response = Global.getIdcClient().sendRequest(userContext, dataBinder);
            DataBinder binder = ridc_response.getResponseAsBinder();
            DataResultSet obj = binder.getResultSet("DOC_INFO");
            DataResultSetRow ob = (DataResultSetRow)obj.getRows().get(0);
            imgDid = ob.get(fielGetValue).toString();

        } catch (IdcClientException e) {
            e.printStackTrace();

        }
        return imgDid;
    }
}
